package com.sinodata.bsm.cicp.collector.emc;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import ch.ethz.ssh2.Session;
import ch.ethz.ssh2.StreamGobbler;

public class EventParse {

    public static synchronized List<Event> parse(Session session) throws ParseException, IOException {
        List<Event> events = new ArrayList<Event>();
        InputStream stdout = new StreamGobbler(session.getStdout());
        @SuppressWarnings("resource")
        BufferedReader br = new BufferedReader(new InputStreamReader(stdout));
        StringBuilder stringBuilder = new StringBuilder();
        while (true) {
            String line = br.readLine();
            if (line == null)
                break;
            stringBuilder.append(line);
        }
        String[] symresults = Pattern.compile("Symmetrix\\s+ID:").split(stringBuilder);
        SimpleDateFormat df = new SimpleDateFormat("EEE MMM dd HH:mm:ss yyyy", Locale.ENGLISH);
        for (int i = 1; i < symresults.length; i++) {
            String[] eventresults = Pattern.compile("Event\\s+at").split(symresults[i]);
            Matcher mat = Pattern.compile("(.*)Time\\s+Zone").matcher(eventresults[0]);
            String symmetrix = "";
            while (mat.find()) {
                symmetrix = mat.group(1).trim();
            }
            for (int j = 1; j < eventresults.length; j++) {
                Matcher matcher = Pattern.compile("\\s*(.+):\\s*Reporting\\s*Director\\s*:(.+)Source\\s*:(.+)Category\\s*:\\s*+(\\S+)\\s*+(Symmetrix\\s*Device\\s*:(.+))?Severity\\s*:(.+)Numeric\\s*Code\\s*:(.+)Event\\s*Code\\s*Symbol\\s*:(.+)Description\\s*:(.*)$").matcher(eventresults[j]);
                while (matcher.find()) {
                    Event event = new Event();
                    event.setSid(symmetrix);
                    event.setRepDir(matcher.group(2).trim());
                    event.setSource(matcher.group(3).trim());
                    event.setCategory(matcher.group(4).trim());
                    event.setDevice(matcher.group(6) == null ? null : matcher.group(6).trim());
                    event.setSeverity(EventSeverity.parseEventSeverity(matcher.group(7).trim()));
                    event.setNumCode(matcher.group(8).trim());
                    event.setEventCode(matcher.group(9).trim());
                    event.setDesc(matcher.group(10).trim());
                    event.setDate(df.parse(matcher.group(1).trim()));
                    events.add(event);
                }
            }
        }
        return events;
    }
}
